package com.hylc.biz.ui.activity;

import static com.xls.commonlibrary.arouter.path.APath.BIZ_HOME_ACTIVITY;
import static com.xls.commonlibrary.constant.BroadAction.ACTION_BR_WEIXIN_LOGIN;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_AD_INIT_SUCCESS;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_LOGIN_DISSMISS_DIALOG;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_WX_INFO_GET_SUCCESS;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_UNION_ID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hylc.biz.R;
import com.hylc.biz.ui.br.Br;
import com.hylc.biz.ui.update.UpdateUtil;
import com.orhanobut.logger.Logger;
import com.xls.boxlibrary.WebviewActivity;
import com.xls.boxlibrary.dilog.LoginDialog;
import com.xls.boxlibrary.dilog.YSZCDialog;
import com.xls.boxlibrary.network.RequestCallBack;
import com.xls.boxlibrary.network.RequestManager;
import com.xls.boxlibrary.network.RetrofitBase;
import com.xls.boxlibrary.statusbar.StatusBarUtil;
import com.xls.boxlibrary.utils.LUtils;
import com.xls.boxlibrary.utils.SPUtils;
import com.xls.boxlibrary.utils.TUtils;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.ad.adn.gm.TTAdManagerHolder;
import com.xls.commonlibrary.arouter.path.APath;
import com.xls.commonlibrary.arouter.path.RouterUtil;
import com.xls.commonlibrary.base.BaseActivity;
import com.xls.commonlibrary.http.Api;
import com.xls.commonlibrary.http.RetrofitHelper;
import com.xls.commonlibrary.http.RxLifecycle;
import com.xls.commonlibrary.http.Transformer;
import com.xls.commonlibrary.http.biz.CodeRewardUtil;
import com.xls.commonlibrary.http.exception.ThrowableUtil;
//import com.xls.commonlibrary.risk.RiskUtil;
import com.xls.commonlibrary.update.CheckUpdateUtil;
import com.xls.commonlibrary.util.ActivityManager;
import com.xls.commonlibrary.util.ChannelUtils;
import com.xls.commonlibrary.util.IsInstallApp;
import com.xls.commonlibrary.util.LoginUtil;
import com.xls.commonlibrary.util.LogoutUtil;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.PermissionUtil;
import com.xls.commonlibrary.util.TokenUtil;
import com.xls.commonlibrary.util.UriUtil;
import com.xls.commonlibrary.util.VersionCodeUtil;
import com.xls.commonlibrary.util.eventbus.MessageEvent;
import com.xls.commonlibrary.util.oaid.OaidUtil;
import com.xls.commonlibrary.wxapi.WxUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

@Route(path = BIZ_HOME_ACTIVITY)
public class HomeActivity extends BaseActivity {

    boolean installedWechat;//是否安装微信

    View layout_wechat;
    TextView textView;

    private LocalBroadcastManager localBroadcastManager;
    Br mBroadcastReceiver;//微信登录广播
    IntentFilter intentFilter;


    CheckBox cb_home_xieyi;
    TextView tv_home_fuwuxieyi;
    TextView tv_home_yinsizhengce;

    ImageView home_renwu;

    /**
     * 注册微信登录广播监听
     */
    void initBr() {
        mBroadcastReceiver = new Br();
        intentFilter = new IntentFilter();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter.addAction(ACTION_BR_WEIXIN_LOGIN);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        setViewNOTitle();
        OaidUtil.getOaid(this);//获取oaid

        installedWechat = IsInstallApp.isWeixinAvilible(this);
        Logger.d("==========isWeixinAvilible=============:" + installedWechat);
        if (!installedWechat) {
//            Toaster.show("微信未安装！");
        }

        initBr();
        // 必要权限
        TTAdManagerHolder.get().requestPermissionIfNecessary(this);
        initView();

        PermissionUtil.getInstance().getPermission(HomeActivity.this, null);


        // todo  一天刷新一次，不能每次进app都刷新
        // 单独激励广告位
        if (CodeRewardUtil.getInstance().isNeedUpdate()) {
            // get所有广告位
            CodeRewardUtil.getInstance().getAdCodeAll(this, isSuccess -> {

            });
        }

        // test
//        ScratchDialog.newInstance(this).show();
//        TimerDialog.newInstance(this).show();

        // test crash
//        CrashReport.testJavaCrash();
//        CrashReport.testJavaCrash();
//        CrashReport.testJavaCrash();

//        autoLogin();
        if (SPUtils.isFirstOpenApp(this)){
            new YSZCDialog(this).show();
        }
        ApplicationInfo appInfo = null;
        try {
            appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (appInfo!=null){
            String data = appInfo.metaData.getString("login_bg");
            if (!TextUtils.isEmpty(data)){
                int drawableId = getDrawableIdByName(this, data);
                if (drawableId!=0){
                    home_renwu.setBackgroundResource(drawableId);
                }
            }
        }

    }


    public int getDrawableIdByName(Context context, String name) {
        Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier(name, "drawable", context.getPackageName());
        return resourceId;
    }

    void initView() {// find views
        cb_home_xieyi = findViewById(R.id.home_xieyi);
        cb_home_xieyi.setChecked(true); // 默认勾上

        tv_home_fuwuxieyi = findViewById(R.id.home_fuwuxieyi);
        tv_home_yinsizhengce = findViewById(R.id.home_yinsizhengce);

        textView = findViewById(R.id.tv_weixin);// 屑：旧版本用不了vb
        layout_wechat = findViewById(R.id.layout_wechat);// 屑：旧版本用不了vb
        textView.setOnClickListener(v -> {
            if (!cb_home_xieyi.isChecked()) {
                TUtils.showShort(this, "请阅读并同意《服务协议》和《隐私政策》");
                return;
            }
            if (!installedWechat) {
//                Toaster.show("请安装微信！");
            }

            showLoginDialog();

            if (TextUtils.isEmpty(MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID))) {

                Logger.d("=========微信未授权  去微信授权==================");

                // 微信未授权  去微信授权
                WxUtil.getInstance().loginWechat(this);
            } else {
                Logger.d("=========微信已授权  直接登陆==================");

                // 微信已授权  直接登陆
                loginAccount();

            }

        });

        findViewById(R.id.home_fuwuxieyi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        findViewById(R.id.home_yinsizhengce).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        cb_home_xieyi.setOnCheckedChangeListener((compoundButton, b) -> {

        });

        tv_home_fuwuxieyi.setOnClickListener(view -> {
           WebviewActivity.start(this,"http://182.92.140.54/index.php/%e7%94%a8%e6%88%b7%e5%8d%8f%e8%ae%ae/");
//           UriUtil.gotoWeb(HomeActivity.this, "http://www.heyilianchuang.top/%E7%94%A8%E6%88%B7%E5%8D%8F%E8%AE%AE.html");
        });

        tv_home_yinsizhengce.setOnClickListener(view -> {
            WebviewActivity.start(this,"http://182.92.140.54/index.php/%e5%a4%9a%e5%a4%9a%e9%92%93%e9%b1%bc%e9%9a%90%e7%a7%81%e6%94%bf%e7%ad%96/");
//            UriUtil.gotoWeb(HomeActivity.this, "http://www.heyilianchuang.top/%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96.html");
        });
        home_renwu=findViewById(R.id.home_renwu);
        findViewById(R.id.tv_url).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UriUtil.gotoWeb(HomeActivity.this, "http://beian.miit.gov.cn");
            }
        });

    }

    LoginDialog loginDialog;

    private void showLoginDialog() {
        loginDialog = new LoginDialog(this);
        loginDialog.show();
    }

    private void dissmissDialog() {
        if (loginDialog != null && loginDialog.isShowing()) loginDialog.dismiss();
    }

    void autoLogin() {
        // todo 勾选了才自动登陆吧
        boolean isChecked = cb_home_xieyi.isChecked();
        // 自动登录
        if (!TextUtils.isEmpty(MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID)) && isChecked) {
            Logger.d("=========微信已授权  自动登陆==================");
            showLoginDialog();
            loginAccount();
        }
    }

    void checkUpdate() {
        // 先授权才能读写sd
        CheckUpdateUtil.getInstance().checkUpdate(this, updateVersionResult -> {
            boolean needUpdate = VersionCodeUtil.isNeedUpdate(updateVersionResult);

            if (needUpdate) {
                UpdateUtil.getInstance().down(this, updateVersionResult);
            } else {
                // 没有更新的才去自动登陆
                // todo 勾选了才自动登陆吧
                boolean isChecked = cb_home_xieyi.isChecked();
                // 自动登录
                if (!TextUtils.isEmpty(MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID)) && isChecked) {
                    Logger.d("=========微信已授权  自动登陆==================");
                    showLoginDialog();
                    loginAccount();
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //步骤4：调用LocalBroadcastManager单一实例的registerReceiver（）方法进行动态注册
        localBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //取消注册应用内广播接收器
        localBroadcastManager.unregisterReceiver(mBroadcastReceiver);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消下载task
        UpdateUtil.getInstance().cancel();
    }

    // 登陆服务器
    void loginAccount() {

        // wx id check
        if (TextUtils.isEmpty(MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID))) {
            Logger.d("wx id is null!!");
            return;
        }


        LoginUtil.getInstance().getLoginParams(this, map -> {
//            WithdrawalUtil.getInstance().loginBox(this, map);
            login(map);
        });
    }
    public void clearCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) { e.printStackTrace(); }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
    @Override
    public void onEventReceived(MessageEvent event) {
        super.onEventReceived(event);

        Logger.d("==========onEventReceived================");
        Logger.d(event);

        if (EVENT_WX_INFO_GET_SUCCESS.equals(event.getCode())) {
            // 微信获取信息成功
            loginAccount();

        } else if (EVENT_AD_INIT_SUCCESS.equals(event.getCode())) {


//            gotoGame();
        } else if (TextUtils.equals(EVENT_LOGIN_DISSMISS_DIALOG, event.getCode())) {
            dissmissDialog();
        }


    }

    // 先绑定渠道,再跳入游戏页面 todo
    void gotoGame() {
        try {
            userReg(this, MMKVUtil.getInstance().getKV().decodeString(KEY_WX_UNION_ID));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    void jump2Game() {
//        Toaster.show("广告数据初始化成功,进入游戏");
        // 游戏页面
        // open game
//        startActivity(new Intent(HomeActivity.this, MainActivity.class));

        // use arouter jump
//        ARouter.getInstance().build(APath.DDX_GAME).navigation();

        // todo 第三步 检查渠道   xxxxxxxxxx

        CheckUpdateUtil.getInstance().checkUpdate(HomeActivity.this, updateVersionResult -> {

            // 第四步  1不需要更新-跳转入游戏   2需要更新-去更新流程
            boolean needUpdate = VersionCodeUtil.isNeedUpdate(updateVersionResult);
            if (needUpdate) {
                // todo 需检测SD权限ok了，才去下载，升级 xxxxxxxxx

                PermissionUtil.getInstance().getPermission(HomeActivity.this, s -> {
                    UpdateUtil.getInstance().down(this, updateVersionResult);
                });

            } else {
                gameJump();
            }

        });


    }

    // 跳转入游戏
    void gameJump() {
        // 点点消 game
        RouterUtil.jump(APath.DDX_GAME);
        // 关闭自己
        ActivityManager.finishActivity(HomeActivity.this);
    }


    public void userReg(Activity activity, String unionId) throws JSONException {
        String channel = ChannelUtils.getChannel(activity);
        LUtils.v("channel---", "channel---" + channel);
        LUtils.v("unionId---", "unionId---" + unionId);


        if (TextUtils.isEmpty(channel) || TextUtils.equals(channel, unionId)) {
            jump2Game();
            return;
        }

        JSONObject data = new JSONObject();
        data.put("unionId", unionId);
        data.put("parentUnionId", channel);


        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data.toString());


        RetrofitBase.getInstace(this).setSubscribe(this, RequestManager.getInstance(this).userReg(body), new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
//                SPUtils.savechannel(activity, channel);

                jump2Game();
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                jump2Game();
            }
        });
    }


    @SuppressLint("CheckResult")
    void login(Map<String, String> params) {
//        TToast.show(this, "login");


//        RiskUtil.getInstance().reportRisk("login");


        // 请求接口,返回Result
        RetrofitHelper.getInstance().create(Api.class).appLogin(params).compose(Transformer.transform()).compose(RxLifecycle.bindRxLifecycle(this)).subscribe(result -> { // lambda 不用写泛型了省的总改了
            //                       ，取消登陆  销毁登陆弹窗
            EventBus.getDefault().post(new MessageEvent(EVENT_LOGIN_DISSMISS_DIALOG, ""));
            if (1 == result.getCode()) {
                // 成功
                Logger.d("登陆成功");
                Logger.d(result.getData());


                // toast("登陆成功");

                // save Token
                TokenUtil.getInstance().saveToken(result.getData().getToken());
                TokenUtil.getInstance().saveGameType(result.getData().getGameType(),this);
                // todo save user info


                // save
//                        if (result.getData().getPlayList() != null && result.getData().getPlayList().size() > 0) {
//                            AdSetCacheUtil.getInstance().savePlayList(result.getData().getPlayList());
//                        }
//                        if (result.getData().getEditList() != null && result.getData().getEditList().size() > 0) {
//                            //  查询四家ecpm，分别上传服务器
//                            AdSetCacheUtil.getInstance().saveEditList(result.getData().getEditList());
//
//                            Set<String> editSet = AdSetCacheUtil.getInstance().getEditList();
//                            EcpmUtil.getInstance().get4Ecpm(HomeActivity.this, editSet);
//                        } else {
//                            // 没有ecpm要补的，进入游戏页面
//                            gotoGame();
//
//                        }
//                // 改为sigmob，不用补ecpm了
//                if (BuildConfig.DEBUG){
////            开启debug跳过校验渠道，测试使用
//                    gameJump();
//                }else {
//                    gotoGame();
//                }
                jump2Game();
                // todo xxxxxx 调用顺序改为： 1登录服务器成功login  2绑定渠道 gotoGame()  [3需要更新渠道包，升级updateVersion]  4进入游戏jump2Game()


            } else {
                // 登陆错误
                toast(result.getMsg());

                // 登陆失败 清空旧用户缓存
                LogoutUtil.clearCache();
            }
        }, throwable -> {

            // 登陆失败 清空旧用户缓存
            LogoutUtil.clearCache();


            // 处理 Retrofit 报错
            toast("失败信息：" + throwable.toString());

            ThrowableUtil.getInstance().handleThrowable(throwable);
        });

    }

    private void setViewNOTitle() {
        /*
         *  当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
         */
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        /*
         * 设置状态栏透明
         */
        StatusBarUtil.setTranslucentStatus(this);
        /*
         *一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
         *所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
         */
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
             /*如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
             这样半透明+白=灰, 状态栏的文字能看得清
             */
            StatusBarUtil.setStatusBarColor(this,0x55000000);
        }
        StatusBarUtil.setRootViewFitsSystemWindows(this,false);
    }

}
